<?php
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
require_once '../../Classes/Babel.php';
class sdf2db{
	private $config;
	function __construct(){
		$this->config = new Zend_Config(require '../inc/dbcnf.php');
	}
	private function db(){
		return Zend_Db::factory($this->config->db_test);
	}
	function procsdf($sdfpath){
		$babel = new Babel();
		$c = file_get_contents($sdfpath);//文件内容
		$c = str_replace("\r\n", "\n", $c);
		$c = str_replace("\n", "{#n#}", $c);
		$chems = explode('$$$${#n#}', $c);
		foreach($chems as $chem){
			$chemstrs = explode("M  END", $chem);
			$mol = ltrim($chemstrs[0]);
			$mol .= "M  END{#n#}";
			$mol = preg_replace("/^.*?{#n#}/", "{#n#}", $mol);
			$mol = preg_replace("/OpenBab/", "SmartChem", $mol);
			//echo $mol;exit;
			$smile = $babel->molecule_to_smiles($mol);
			if(!$smile)
				continue;
			$attrs = explode( "{#n#}{#n#}",$chemstrs[1]);
			$cols = array();
			foreach($attrs as $attr){
				try{
				$attr = ltrim($attr,"{#n#}> ");
				$attrkv = explode("{#n#}",$attr);
				$cols[$attrkv[0]]=$attrkv[1];
				}catch(Exception $e){}
			}
			$this->db()->query("insert into compound(casno,compoundno,compoundname,compoundnameen,mol,smile,userid,username,projectid,addtime,modtime) values(:casno,:compoundno,:compoundname,:compoundnameen,:mol,:smile,:userid,:username,:projectid,:addtime,:modtime)",
					//array("casno"=>$cols["<CAS>"],"compoundno"=>time(),"compoundname"=>$cols["<SUPPLIER_NAME>"],"compoundnameen"=>$cols["<SUPPLIER_NAME>"],"mol"=>$mol,"smile"=>$smile,"userid"=>1,"username"=>"chem","projectid"=>1,"addtime"=>date("Y-m-d H:m",time()),"modtime"=>date("Y-m-d H:m",time())));
					array("casno"=>$cols["<chembl_id>"],"compoundno"=>$cols["<chembl_id>"],"compoundname"=>$cols["<chembl_id>"],"compoundnameen"=>$cols["<chembl_id>"],"mol"=>$mol,"smile"=>$smile,"userid"=>1,"username"=>"chem","projectid"=>1,"addtime"=>date("Y-m-d H:m",time()),"modtime"=>date("Y-m-d H:m",time())));
			$id = $this->db()->fetchOne("select max(id) from compound");
			echo "#####".$id;
			$babel->mol2gif($id, $mol);
			if($id>20000)
			return;
		}
	}
}
$obj = new sdf2db();
$obj->procsdf("/data/yuecl/cccc.sdf");
system("chmod -R www-data:www-data '/home/soooner/data/webroot/userbiz/public/svg'");